package com.hefan.oms.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.tiger.util.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.oms.bean.RedPackQiangVo;
import com.hefan.oms.itf.RedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/12.
 * RedpacketQiangListener是抢红包用的
 */
@Component
public class RedPacketQiangListener implements GLLMessageListener {

    @Resource
    private RedPacketService redPacketService;

    private Logger logger = LoggerFactory.getLogger(RedPacketQiangListener.class);

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFANTV_REDQ;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFANTV_REDQ_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFANTV_REDQ_TEST;
    }


    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {

        String realTopic = message.getTag();
        logger.info("RedPacketQiangListener", message.getTopic(), realTopic, new String(message.getBody()));
        try {
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (!CollectionUtils.isEmpty(map) && map.containsKey("redPackQiangVo")) {
                String redPacketStr = (String)map.get("redPackQiangVo");
                logger.info("抢红包队列接受参数{}",redPacketStr);

                RedPackQiangVo redPackQiangVo = JSON.parseObject(redPacketStr, RedPackQiangVo.class);

                redPacketService.grapRedPacket(redPackQiangVo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Action.ReconsumeLater;
        }

        return Action.CommitMessage;
    }

}
